from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from config import Config
from logging.handlers import RotatingFileHandler
from flask_migrate import Migrate
# from flaskr.db import get_db, init_db
import os, logging


db = SQLAlchemy()
migrate = Migrate()
login_manager = LoginManager()
# mailbox of message queues
mailbox = {}


def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)
    
    db.init_app(app)
    # with app.app_context():
    #     init_db()
    migrate.init_app(app, db)
    login_manager.init_app(app)

    from app.main import main as main_bp
    app.register_blueprint(main_bp)

    from app.auth import auth as auth_bp
    app.register_blueprint(auth_bp, url_prefix="/auth")
    
    from app.user import bp as user_bp
    app.register_blueprint(user_bp, url_prefix='/user')

    from app.admin import admin as admin_bp
    app.register_blueprint(admin_bp, url_prefix='/admin')


    """ Many config here
    """


    if not app.debug:
        if not os.path.exists('logs'):
            os.mkdir('logs')
        file_handler = RotatingFileHandler(
            'logs/server.log', maxBytes=10240, backupCount=10)
        file_handler.setFormatter(logging.Formatter(
            '%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
        file_handler.setLevel(logging.INFO)
        app.logger.addHandler(file_handler)

        app.logger.setLevel(logging.INFO)
        app.logger.info('Server startup')

    return app


from app import models
